package com.invengo.base.utils;

import android.annotation.SuppressLint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class ZipUtil {

    public static Document getDatasetByString(String value) {
        try {
            String cc = GZipDecompressString(value);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(cc));
            return builder.parse(is);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getStringByDataset(String ds) {
        return GZipCompressString(ds);
    }

    @SuppressLint("NewApi")
    public static String GZipCompressString(String rawString) {
        if (rawString == null || rawString.length() == 0) {
            return "";
        } else {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                GZIPOutputStream gzip = new GZIPOutputStream(bos);
                gzip.write(rawString.getBytes("UTF-8"));
                gzip.close();
                byte[] zippedData = bos.toByteArray();
                return Base64.getEncoder().encodeToString(zippedData);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    @SuppressLint("NewApi")
    public static String GZipDecompressString(String zippedString) {
        if (zippedString == null || zippedString.length() == 0) {
            return "";
        } else {
            try {
                byte[] zippedData = Base64.getDecoder().decode(zippedString);
                ByteArrayInputStream bis = new ByteArrayInputStream(zippedData);
                GZIPInputStream gzip = new GZIPInputStream(bis);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = gzip.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }
                return new String(bos.toByteArray(), "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}


